package com.example.demo.utils;

import lombok.extern.slf4j.Slf4j;

import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import java.nio.charset.StandardCharsets;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

/**
 * @author Liunh
 */
@Slf4j
public class AlgorithmDefine {

    /**
     * key
     * 确保使用的密钥长度与算法要求的长度匹配。
     * AES获取的key >=16
     * DES获取的key 8
     */
    public static final String KEY = "abcdefg0123456789";

    /**
     * 非对称加密算法MD5
     */
    public static final String ALGORITHM_MD5 = "MD5";

    /**
     * 非对称加密算法SHA
     */
    public static final String ALGORITHM_SHA1 = "SHA-1";

    /**
     * <p>非对称加密算法:</p>
     * <p>MAC算法可选以下多种算法</p>
     * <p>
     * <p>HmacMD5 HmacSHA1 HmacSHA256 HmacSHA384 HmacSHA512</p>
     */
    public static final String ALGORITHM_MAC = "HmacMD5";

    public static final String ALGORITHM_DES = "DES";

    public static final String ALGORITHM_DESEDE = "DESede";

    public static final String ALGORITHM_BLOWFISH = "Blowfish";

    public static final String ALGORITHM_HMAC_SHA = "HmacSHA256";

    public static final String ALGORITHM_AES = "AES";

    public static final String ALGORITHM_RSA = "RSA";

    /**
     * 转换规则  默认情况下, 加密模式和填充模式为 : ECB/PKCS5Padding
     */
    public static final String AES_ECB_PADDING = "AES/ECB/PKCS5Padding";
    public static final String DES_ECB_PADDING = "DES/ECB/PKCS5Padding";
    public static final String AES_CBC_PADDING = "AES/CBC/PKCS5Padding";
    public static final String DES_CBC_PADDING = "DES/CBC/PKCS5Padding";


    public static SecretKey getSecretKey(String key, String algorithmType) {
        try {
            //获取key的构造器
            KeyGenerator keyGenerator = KeyGenerator.getInstance(algorithmType);
            //密钥加强
            SecureRandom secureRandom = new SecureRandom();
            secureRandom.setSeed(key.getBytes(StandardCharsets.UTF_8));
            //构造器初始化 keysize 初始大小为128 一次加64
            keyGenerator.init(256, secureRandom);
            return keyGenerator.generateKey();
        } catch (NoSuchAlgorithmException e) {
            log.error("算法类型有误，获取密钥失败", e);
            throw new RuntimeException("算法类型有误，获取密钥失败！");
        }
    }


}
